/* eslint-disable no-prototype-builtins */
import { Vue, Component } from 'vue-property-decorator';
import { Dictionary, FormListConfig, AnchorConfig } from '@/typings';
import { transformFields } from '@/utils';
import commonApi from '@/api/common-api/index';
import { Tools } from '@/utils/tools';
import { PermissionConfig } from '@/store/modules/common-module';

@Component({})
export default class detailMixins extends Vue {
    // [x: string]: any
    m_moduleName: string = '';
    anchorList: AnchorConfig[] = []; // 外层维护
    customerFieldsTabs: any[] = []; // 外层维护
    formData: Dictionary<any> = {}; // 外层维护
    m_render: number = 0; // 用于刷新组件
    m_customerFiledsconfig: string[] = []; // 这里存储是否引用上级单据的值的自定义字段
    m_customerMapTemp: Dictionary = {};
    get m_billPageSize() {
        return localStorage.getItem('Bill_Page_Record_Quantity') || 2;
    }
    created() {
        this.m_moduleName = JSON.parse(JSON.stringify(this.$route.meta.moduleId));
    }
    m_resetTotalColumn(totalColumn: Dictionary) {
        Object.keys(totalColumn).forEach((item) => {
            if (totalColumn[item]) {
                Object.keys(totalColumn[item]).forEach((k) => {
                    totalColumn[item][k] = 0;
                });
            }
        });
        this.$store.commit(`${this.m_moduleName}/SET_BILLTOTAL_INFO`, totalColumn);
    }
    // 对返回的自定义字段表单进行格式化
    m_transformCustomerFileds(arr: any[], formdata: Dictionary): FormListConfig[] {
        this.m_customerFiledsconfig = [];
        return arr.map((item) => {
            const obj: FormListConfig = {
                label: item.label,
                value: item.columnName,
                type: item.typeName
            };
            if (item.length) {
                obj.config = {
                    maxlength: item.length
                };
            }
            if (item.loadPreBillFlag) {
                this.m_customerFiledsconfig.push(item.columnName);
            }

            // 如果是必填 则添加匹配规则
            if (item.requireFlag) {
                obj.rules = [
                    {
                        required: true,
                        message: `请输入${item.label}`,
                        trigger: item.type === 'select' ? 'change' : 'blur'
                    }
                ];
                // this.$set(formdata, item.columnName, '')
                formdata[item.columnName] = '';
            }
            // 如果有下拉框 则格式化下拉框值
            if (item.options) {
                obj.options = transformFields(item.options, {
                    label: 'value',
                    value: 'id'
                });
            }

            const defaultValue = item.options && item.defaultValue ? Number(item.defaultValue) : item.defaultValue || item.defaultDate;
            formdata[item.columnName] = defaultValue;
            return obj;
        });
    }
    // 根据上级单据带出来的数据 是否显示用上级单据的自定义字段值
    m_setCustomerFieldsValue(customFieldMap: Dictionary<string>, mainFormName?: string) {
        Object.keys(customFieldMap).forEach((item) => {
            if (this.formData.customFieldMap && (this.formData.customFieldMap as Object).hasOwnProperty(item)) {
                // 如有自定义字段有设置引用上级单据 则赋值
                if (this.m_customerFiledsconfig.includes(item)) {
                    if (mainFormName) {
                        this.$set(this.formData[mainFormName], item, customFieldMap[item]);
                    } else {
                        this.$set(this.formData, item, customFieldMap[item]);
                    }
                    this.$set(this.formData.customFieldMap, item, customFieldMap[item]);
                }
            }
        });
    }
    // 获取模块下面的自定义字段
    async m_getModuleCustomerFiledsFn(fixTabs: Dictionary, formdata: Dictionary, realModuleId: string | number) {
        this.anchorList = this.authorityTab();
        const res = await this._post({
            url: `${commonApi.getModuleCustomerFields}/${realModuleId}`
        });
        // this.
        if (res.code === 0) {
            // system_column_property 是设置主表字段的必填
            const { groupColumnMap, systemColumnMap } = res.data;
            if (systemColumnMap && systemColumnMap.system_column_property) {
                const matchMainTab = fixTabs['system_column_property'];
                systemColumnMap.system_column_property
                    .filter((item) => item.requireFlag)
                    .forEach((requireItem) => {
                        this[matchMainTab].forEach((fields) => {
                            if (fields.value === requireItem.propertyName) {
                                this.$set(fields, 'rules', [
                                    {
                                        required: true,
                                        message: `${fields.type === 'select' ? '请选择' : '请输入'}${fields.label}`,
                                        trigger: fields.type === 'select' ? 'change' : 'blur'
                                    }
                                ]);
                            }
                        });
                    });
            }
            // const customerObj: Dictionary = {}
            // 用户存储自定义字段的默认值
            this.m_customerMapTemp = {};
            for (const key in groupColumnMap) {
                // 如果固定的 tabs 里面有 自定义字段 则 合并
                if (fixTabs[key]) {
                    const matchTab = fixTabs[key];

                    this[matchTab] = [...this[matchTab], ...this.m_transformCustomerFileds(groupColumnMap[key], this.m_customerMapTemp)];
                } else {
                    // 组装 自定义字段 tabs
                    const item = groupColumnMap[key][0];
                    const anchor: AnchorConfig = {
                        label: item.groupName,
                        value: key,
                        ref: key
                    };
                    this.anchorList = [...this.anchorList, anchor];
                    this.customerFieldsTabs.push({
                        ...anchor,
                        // formList: this.m_transformCustomerFileds(groupColumnMap[key], this.formData.customFieldMap)
                        formList: this.m_transformCustomerFileds(groupColumnMap[key], this.m_customerMapTemp)
                    });
                }
            }
            for (const keys in this.m_customerMapTemp) {
                this.$set(formdata, keys, this.m_customerMapTemp[keys]);
                // 兼容对象值为Null
                if (!(this.formData.customFieldMap && typeof this.formData.customFieldMap === 'object')) {
                    this.$set(this.formData, 'customFieldMap', Object.create(null));
                }
                this.$set(this.formData.customFieldMap, keys, this.m_customerMapTemp[keys]);
            }
        }
    }
    // 保存处理自定义字段map
    m_rebuildCustomerMap(name: string) {
        if (!this.formData[name]) {
            console.error(`formData属性检测不到${name}对象`);
            return {};
        }
        const customFieldMap: object = {};
        for (const key in this.m_customerMapTemp) {
            if (Object.keys(this.formData[name]).includes(key)) {
                customFieldMap[key] = this.formData[name][key];
                delete this.formData[name][key];
            }
        }
        this.formData[name]['customFieldMap'] && delete this.formData[name]['customFieldMap'];
        return customFieldMap;
    }
    // 保存处理货品明细自定义字段map
    m_rebuildGoodsCustomerMap(array: any[], key?: string) {
        const FileMap = this.$store.state[this.$route.meta.moduleId].v_goodsCustomFiledMap;
        // 兼容多货品明细视图的单据模块例如发货单
        const target = key ? FileMap[key] : FileMap;
        return array.map((em) => {
            em.customFieldMap = Object.create(null);
            if (target && target.customer) {
                console.log('target.customer', target.customer);
                target.customer.forEach((k) => {
                    // em.customFieldMap[k] = em[k] || ''
                    em.customFieldMap[k.field] = em[k.field] || '';
                    // delete em[k]
                });
            }
            // target.customer && target.customer.forEach(k => {
            //   // em.customFieldMap[k] = em[k] || ''
            //   em.customFieldMap[k.field] = em[k.field] || ''
            //   // delete em[k]
            // })
            return em;
        });
    }
    // 获取详情格式化货品明细自定义字段
    m_customGoodsCustomer(array: any[]) {
        return Array.isArray(array)
            ? array.map((em) => {
                  const { customFieldMap } = em;
                  if (customFieldMap) {
                      for (const k in customFieldMap) {
                          em[k] = customFieldMap[k];
                      }
                  }
                  return em;
              })
            : [];
    }
    // 处理tabs权限
    authorityTab() {
        //   if(this.$store[this.moduleId])
        const permissionObj: PermissionConfig = this.$store.state[this.$route.meta.moduleId].v_permission;
        if (permissionObj) {
            return this.anchorList.reduce((k: AnchorConfig[], m) => {
                if (permissionObj.page.browse.includes(m.value as string) || !m.isValidatePermisssion) {
                    m.edit = !m.isValidatePermisssion ? true : permissionObj.page.edit.includes(m.value as string);
                    k.push(m);
                }
                return k;
            }, []);
        } else {
            return this.anchorList.map((item) => {
                return Object.assign({}, item, { edit: true });
            });
        }
    }
    // 处理工作流状态
    m_dealActivityStatus(status: number, flowStatus: number, flowDto: Dictionary) {
        // this.$store.dispatch(`${this.m_moduleName}/v_setBtnsAuth`, status + '')
        this.$store.commit(`${this.m_moduleName}/SET_PENDING_STATUS`, flowStatus);
        console.log('status', status);
        // 如果有审核工作流 则把按钮置为 审批状态
        //  审批状态 0和4 代表初始化 和 审批流程结束
        this.$store.dispatch(`${this.m_moduleName}/v_setBtnsAuth`, flowDto.flowFlag && ![0, 4].includes(flowStatus) ? 'pendingAudit' : status + '');
        // 如果有发起审核 审批的权限
        if (flowDto.flowCheckFlag) {
            this.$store.commit(`${this.m_moduleName}/SET_BTN_AUTH`, {
                key: 'audit',
                flag: true
            });
        }
        // 如果有发起反审核 反审核审批的权限 并且单据状态为审核状态才可以反审核
        if (flowDto.flowUnCheckFlag && status === 1) {
            this.$store.commit(`${this.m_moduleName}/SET_BTN_AUTH`, {
                key: 'unaudit',
                flag: true
            });
        }
        // 如果有发起作废 反审核审批的权限 并且单据状态为审核状态才可以作废
        if (flowDto.flowInvalidFlag && status === 1) {
            this.$store.commit(`${this.m_moduleName}/SET_BTN_AUTH`, {
                key: 'invalid',
                flag: true
            });
        }
        // 只有作废的单据才能恢复 并且是否有恢复的权限
        if (flowDto.flowUnInvalidFlag && status === 3) {
            this.$store.commit(`${this.m_moduleName}/SET_BTN_AUTH`, {
                key: 'restore',
                flag: true
            });
        }
        this.$store.commit(`${this.m_moduleName}/SET_BILL_STATUS`, status + '');
    }
    // 处理新建之后 字段恢复到初始化  如果有自定义字段且保留
    m_reset(content?: string) {
        const date_key = ['billDate', 'buildDate'];
        for (const key in this.formData) {
            if (this.formData[key] instanceof Array) {
                this.$set(this.formData, key, []);
            } else if (this.formData[key] instanceof Object) {
                // 如果是自定义字段集合  值则设置成默认值
                if (key === 'customFieldMap') {
                    for (const customerKey in this.m_customerMapTemp || {}) {
                        // 恢复表头字段的默认值
                        this.$set(content ? this.formData[content] : this.formData, customerKey, this.m_customerMapTemp[customerKey]);
                        // 恢复自定义 TAB 的字段默认值
                        this.$set(this.formData.customFieldMap, customerKey, this.m_customerMapTemp[customerKey]);
                    }
                } else {
                    for (const objectKey in this.formData[key]) {
                        // 恢复表头字段的默认值
                        const defaultValue = date_key.includes(objectKey) ? Tools.getCurrentData(false) : null;
                        // 恢复自定义 TAB 的字段默认值
                        // 如果是主表字段则
                        if (!content) {
                            this.$set(this.formData, objectKey, Array.isArray(this.formData[key][objectKey]) ? [] : defaultValue);
                        } else {
                            this.$set(this.formData[key], objectKey, Array.isArray(this.formData[key][objectKey]) ? [] : defaultValue);
                        }
                    }
                }
            } else {
                const defaultValue = date_key.includes(key) ? Tools.getCurrentData(false) : null;
                this.$set(this.formData, key, defaultValue);
            }
        }
        // this.m_render++
        try {
            this.$store.commit(`${this.$route.meta.moduleId}/CHANGE_PROTOTYPE`, function (state) {
                // 如果有视图面板则清空
                if (state.v_billTotalInfo) {
                    state.v_billTotalInfo.forEach((em) => {
                        em.value && (em.value = 0);
                    });
                }
            });
        } catch (err) {
            console.error(err);
        }
    }

    m_dealSaveAction(res: { data: string | object; msg: any }) {
        if (res.data) {
            const status = this.$store.state[this.m_moduleName].v_status;
            const successMessage = status === 'add' ? 'save' : 'edit';

            // 设置页面状态
            this._message({
                message: this.$t('commonWord.actionSuccess', {
                    action: this.$t('operationGroup.btns')[successMessage]
                }),
                type: 'success'
            });

            // 状态设置 可读
            this.$store.commit(`${this.m_moduleName}/SET_READ_STATUS`, true);

            // 更新 ID
            this.$store.commit(`${this.m_moduleName}/SET_ID`, `${res.data}_${new Date().getTime()}`);
            // this.$store.commit(`${this.m_moduleName}/SET_ROW`, this.$store.state[this.m_moduleName].v_row) // 额外的信息其实是不需要更新，非关键

            // 刷新 list 列表
            this.$store.commit(`${this.m_moduleName}/SET_REFRESH_LIST_TABLE`, new Date().getTime());

            this.$store.commit(`${this.m_moduleName}/SET_STATUS`, '');
        } else {
            this._notify(res.msg);
        }
    }
}
